package com.zyg.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson2.JSON;
import com.zyg.pojo.User;
import com.zyg.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping("")
    public String login(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(User user, String code, HttpSession session){
        String sessionCode = (String) session.getAttribute("code");
        if (!sessionCode.equalsIgnoreCase(code)){
            return "redirect:/";
        }else {
            User u=userService.login(user);
            if (u!=null){
                //存储用户id
                StpUtil.login(u.getId());
                return "redirect:/toindex";
            }else {
                return "redirect:/";
            }
        }
    }

    @RequestMapping("/imgCode")
    @ResponseBody
    public String imgCode(HttpSession session){
        //清除session中的验证码
        session.removeAttribute("code");
        //调用hutool验证码工具类生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        String code = captcha.getCode();
        //将验证码放入session
        session.setAttribute("code",code);
        return JSON.toJSONString(captcha.getImageBase64());
//        //图片转为字符串
//        captcha.getImageBase64();
//    	return "imgCode";
    }
}

